package com.ycsd.invest.order.business.formplugin;

import cn.hutool.core.collection.CollectionUtil;
import kd.bos.bill.AbstractBillPlugIn;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.metadata.IDataEntityProperty;
import kd.bos.entity.datamodel.events.BizDataEventArgs;
import kd.bos.entity.datamodel.events.PropertyChangedArgs;
import kd.bos.entity.plugin.Plugin;
import kd.bos.form.*;
import kd.bos.form.container.Tab;
import kd.bos.form.control.Label;
import kd.bos.form.control.Toolbar;
import kd.bos.form.control.events.*;
import kd.bos.form.events.*;
import kd.bos.form.field.BasedataEdit;
import kd.bos.form.field.TextEdit;
import kd.bos.form.field.events.BeforeF7SelectEvent;
import kd.bos.form.field.events.BeforeF7SelectListener;
import kd.bos.form.operate.FormOperate;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.list.ListShowParameter;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import oadd.org.apache.commons.lang3.StringUtils;
import org.apache.commons.compress.utils.Lists;

import java.util.EventObject;
import java.util.List;

public class OrderInfoForm extends AbstractFormPlugin implements BeforeF7SelectListener,TabSelectListener {
//public class OrderInfoForm extends AbstractFormPlugin implements TabSelectListener {
//public class OrderInfoForm extends AbstractFormPlugin{
//public class OrderInfoForm extends AbstractBillPlugIn {

    @Override
    public void preOpenForm(PreOpenFormEventArgs e) {
        //页面打开前事件

        // 动态注册插件： OrderInfoDynamicPluginTestForm
        // todo
        FormShowParameter formShowParameter = e.getFormShowParameter();
        List<Plugin> plugins = formShowParameter.getFormConfig().getPlugins();
        Plugin plugin = new Plugin();
        plugin.setClassName("com.ycsd.invest.order.business.formplugin.OrderInfoDynamicPluginTestForm");
        plugins.add(plugin);
    }

    @Override
    public void createNewData(BizDataEventArgs e) {
        //新建数据事件

        // 新建数据的时候，设置某几个字段的默认值
        DynamicObject dataEntity = new DynamicObject(this.getModel().getDataEntityType());
        dataEntity.set("i", 1);
        dataEntity.set("j", 2);
        e.setDataEntity(dataEntity);

    }

    @Override
    public void beforeBindData(EventObject e) {
        //数据绑定前

        // 数据绑定前，设置某个控件的显示/隐藏，必录/非必录
        this.getView().setVisible(false, "currencytype");
        TextEdit totalAmount = this.getControl("total_amount");
        totalAmount.setMustInput(true);

    }

    @Override
    public void afterBindData(EventObject e) {
        //数据绑定后

        // 数据绑定后，根据数量1+数量2的值，做运算合计，赋值到数量3控件
        Object i = this.getModel().getValue("i");
        Object j = this.getModel().getValue("j");
        if (i != null && j != null) {
            Integer i1 = Integer.valueOf(i.toString());
            Integer j1 = Integer.valueOf(j.toString());
            Integer n = i1 + j1;
            this.getModel().setValue("n", n);
        }
        // 数据绑定后，查询出当前用户的部门信息，填充到某个文本控件中
        RequestContext requestContext = RequestContext.get();
        long currUserId = requestContext.getCurrUserId();
        DynamicObject userBill = BusinessDataServiceHelper.loadSingle(currUserId, "bos_user");
        DynamicObjectCollection deptEntry = userBill.getDynamicObjectCollection("entryentity");
        List<String> depNames = Lists.newArrayList();
        for (DynamicObject row : deptEntry) {
            String deptName = row.getString("dpt.name");
            depNames.add(deptName);
        }
        if (CollectionUtil.isNotEmpty(depNames)) {
            this.getModel().setValue("order_remark", String.join(",", depNames));
        }
    }

    @Override
    public void registerListener(EventObject e) {
        //注册事件
//        this.addItemClickListeners("tbmain");

        // 注册基础资料F7事件，工具栏按钮、普通按钮、标签事件
        BasedataEdit orderStatus = this.getControl("order_status");
        orderStatus.addBeforeF7SelectListener(this);
        Toolbar tbmain = this.getControl("tbmain");
        tbmain.addItemClickListener(this);
        Label label = this.getView().getControl("label");
        label.addClickListener(this);
        Tab tab = this.getView().getControl("ycsd_tabap");
        tab.addTabSelectListener(this);


    }
//
//    @Override
    public void beforeItemClick(BeforeItemClickEvent evt) {
//        System.out.println();
//        //点击按钮后 执行绑定按钮前
        String itemKey = evt.getItemKey();
        switch (itemKey) {
            case "bar_save": {
                evt.setCancel(true);
                this.getView().showConfirm("是否确认", MessageBoxOptions.OKCancel, new ConfirmCallBackListener("confirmSubmit"));
            }
            default: {
                break;
            }

        }
        // 工具栏按钮点击前，设置取消继续执行
        if (evt.getItemKey().equals("bar_del")) {
            evt.setCancel(true);
        }
    }
//
    @Override
    public void beforeClosed(BeforeClosedEvent e) {
        //页面关闭之前
//        System.out.println();
//        BillShowParameter billShowParameter = new BillShowParameter();
//        billShowParameter.setFormId("ycsd_student_info");
//        billShowParameter.getOpenStyle().setShowType(ShowType.NewWindow);
//        billShowParameter.setPkId("2219166789802153984");
//        billShowParameter.setCaption("点击更多了");
//        getView().showForm(billShowParameter);
        Object i = this.getModel().getValue("i");
        if (i != null && i instanceof Integer && Integer.parseInt(i.toString()) == 1) {
            e.setCancel(true);
            this.getView().showTipNotification("整数1字段的值不能为1");
        }
    }
//
    @Override
    public void beforeDoOperation(BeforeDoOperationEventArgs args) {
        //绑定操作逻辑前
        System.out.println();
        // 操作执行前，设置取消继续执行
        FormOperate formOperate = (FormOperate) args.getSource();
        if (formOperate.getOperateKey().equals("submit")) {
            args.setCancel(true);
        }
    }

    @Override
    public void afterDoOperation(AfterDoOperationEventArgs afterDoOperationEventArgs) {
        //绑定操作逻辑后
        System.out.println();
        // 操作执行后，弹出提示“操作执行成功”
        this.getView().showSuccessNotification("操作执行成功");
    }

    @Override
    public void itemClick(ItemClickEvent evt) {
        //点击按钮

        // 工具栏按钮点击后，弹出一个动态表单二级页面，动态表单关闭后，须返回数据，并触发closedCallBack
        if (evt.getItemKey().equals("bar_print")) {
            FormShowParameter showParameter = new FormShowParameter();
            // 设置子页面编码
            showParameter.setFormId("ycsd_order_info_up");
            // 子页面打开方式
            showParameter.getOpenStyle().setShowType(ShowType.Modal);
            // 设置子页面回调标识
            CloseCallBack callBack = new CloseCallBack(this, "suggestion");
            showParameter.setCloseCallBack(callBack);
            // 打开子页面
            this.getView().showForm(showParameter);

        }
    }
//
    @Override
    public void propertyChanged(PropertyChangedArgs e) {
        //值改变
//        IDataEntityProperty property = e.getProperty();
//        String name = property.getName();
//        ChangeData[] changeSet = e.getChangeSet();
//        for (ChangeData changeData : changeSet) {
//            Object newValue = changeData.getNewValue();
//        }

        // 根据数量1+数量2的值，做运算合计，赋值到数量2控件
        IDataEntityProperty property = e.getProperty();
        String name = property.getName();
        if (name.equals("i") || name.equals("j")) {
            Object i = this.getModel().getValue("i");
            Object j = this.getModel().getValue("j");
            if (i != null && j != null) {
                Integer i1 = Integer.valueOf(i.toString());
                Integer j1 = Integer.valueOf(j.toString());
                Integer m = i1 * j1;
                this.getModel().setValue("m", m);
            }
        }

    }
//
//
    @Override
    public void closedCallBack(ClosedCallBackEvent closedCallBackEvent) {
        //关闭回调
        System.out.println();

        // 弹出的二级页面关闭后，获取二级页面返回的数据，使用message弹出yes/no的弹窗确认框，将数据弹出来显示，提示是否赋值到字段中
        if (closedCallBackEvent != null && closedCallBackEvent.getActionId().equals("suggestion")) {
            Object returnData = closedCallBackEvent.getReturnData();
            if (returnData != null) {
                this.getPageCache().put("suggestion", returnData.toString());
                this.getView().showConfirm("是否填充：" + returnData, MessageBoxOptions.YesNo, new ConfirmCallBackListener("confirmSubmit"));
            }
        }
    }
//
    @Override
    public void confirmCallBack(MessageBoxClosedEvent messageBoxClosedEvent) {
        //确认回调
//        String callBackId = messageBoxClosedEvent.getCallBackId();
//        MessageBoxResult result = messageBoxClosedEvent.getResult();
//        if ("confirmSubmit".equals(callBackId) && result.equals(MessageBoxResult.Yes)) {
//            this.getView().invokeOperation("save");
//        }

        // 确认框点击yes后，将字段填充到字段中显示，点击no不填充
        String callBackId = messageBoxClosedEvent.getCallBackId();
        MessageBoxResult result = messageBoxClosedEvent.getResult();
        if ("confirmSubmit".equals(callBackId) && result.equals(MessageBoxResult.Yes)) {
            String suggestion = this.getPageCache().get("suggestion");
            this.getModel().setValue("closed_value", suggestion);
        }
    }
//
////    @Override
////    public void confirmCallBack(MessageBoxClosedEvent messageBoxClosedEvent) {
////        String callBackId = messageBoxClosedEvent.getCallBackId();
////        if ("confirmSubmit".equals(callBackId)) {
////            if (messageBoxClosedEvent.getResult() == MessageBoxResult.Yes) {
//                BillShowParameter billShowParameter = new BillShowParameter();
//                billShowParameter.setFormId("ycsd_student_info");
//                billShowParameter.getOpenStyle().setShowType(ShowType.Modal);
//                billShowParameter.setPkId("2219166789802153984");
//                billShowParameter.setCaption("点击更多了");
//                getView().showForm(billShowParameter);
                    //打开列表页面
//                ListShowParameter listShowParameter = new ListShowParameter();
//                listShowParameter.setFormId("bos_list");
//                listShowParameter.setBillFormId("ycsd_student_info");
//                listShowParameter.getOpenStyle().setShowType(ShowType.Modal);
//                this.getView().showForm(listShowParameter);
////            }
////        }
////        super.confirmCallBack(messageBoxClosedEvent);
////    }
//
    @Override
    public void beforeF7Select(BeforeF7SelectEvent beforeF7SelectEvent) {
        //基础资料过滤
        System.out.println();

        // 设置基础资料列表的过滤条件
        IDataEntityProperty property = beforeF7SelectEvent.getProperty();
        if (property.getName().equals("order_status")) {
            beforeF7SelectEvent.addCustomQFilter(new QFilter("name", QCP.like, "已%"));
        }
    }
//
    @Override
    public void beforeClick(BeforeClickEvent evt) {
        Label source = (Label) evt.getSource();
        String key = source.getKey();
        if (key.equals("label")) {
            Object closedValue = this.getModel().getValue("closed_value");
            if (closedValue == null || StringUtils.isBlank(closedValue.toString())) {
                this.getView().showErrorNotification("回调的值是空的");
            }
        }
    }

    @Override
    public void click(EventObject evt) {
        Label source = (Label) evt.getSource();
        String key = source.getKey();
        if (key.equals("label")) {
            this.getModel().setValue("i", 1000);
        }

    }
//
    @Override
    public void tabSelected(TabSelectEvent tabSelectEvent) {
        //页签切换
        String subTabKey = tabSelectEvent.getTabKey();
        System.out.println(subTabKey);
        if (subTabKey.equals("ycsd_tabpageap1")) {
            Object m = this.getModel().getValue("m");
            if (m != null) {
                int m1 = Integer.parseInt(m.toString());
                if (m1 <= 90000000){
                    this.getView().showErrorNotification("乘积小于90000000");
                }
            }
        }

    }
}